var UserListItem = Backbone.View.extend({
	tagName : 'tr',

	initialize : function() {
		this.listenTo(this.model, 'destroy', this.remove)
	},

	template : _.template($('#tpl-userList').html()),

	render : function() {
		$(this.el).html(this.template(this.model.attributes));
		return this;
	}

});

var UserListView = Backbone.View.extend({
	el : $('table#userList'),

	events : {
		'click a.delete' : 'deleteUser'
	},

	initialize : function() {
		_.bindAll(this, 'createUser', 'addUserToUserList', 'deleteUser');
		this.model.bind("reset", this.render, this);
		this.model.bind('add', this.renderNewUser, this);
		this.model.bind('remove', this.deleteUserRow, this);

		$('body input#addButton').bind('click', this.createUser);
	},

	render : function(eventName) {
		_.each(this.model.models, function(user) {
			$(this.el).append(new UserListItem({
				model : user
			}).render().el);
		}, this);

		return this;
	},

	renderNewUser : function() {
		$(this.el).append(new UserListItem({
			model : _.last(this.model.models)
		}).render().el);
	},

	addUserToUserList : function() {
		this.model.add(user);
	},

	createUser : function() {

		var user = new User();

		user.attributes.name = $('body input#username').val();
		user.attributes.fullName = $('body input#fullusername').val();
		user.attributes.email = $('body input#email').val();
		user.attributes.notes = $('body input#notes').val();
		user.attributes.isAdmin = $('body input#isAdmin').prop('checked');

		user.save({}, {
			success : addUserToUserList,
			error : function() {
				console.log('error: ' + user.attributes.id + '; '
						+ user.attributes.name);
			}
		});

	},

	deleteUser : function(e) {
		var user = this.model.get(e.target.id);

		user.destroy();
		this.model.remove(user);

	}
});
